/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef _DAL_STRING_H_
#define _DAL_STRING_H_
#include <stdint.h>
#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

#define DEFAULT_STRING                                                                             \
    {                                                                                              \
        0, 0                                                                                       \
    }

// after using this structure, you must call RESET_STRING explicitly,
// otherwise it will cause a memory leak.
typedef struct dal_string_s
{
    char* str;
    uint64_t length;
} dal_string_t;

#define RESET_STRING(obj)                                                                          \
    {                                                                                              \
        free((obj)->str);                                                                          \
        (obj)->length = 0;                                                                         \
    }

#define SET_STRING(obj, c_str, len)                                                                \
    {                                                                                              \
        const char* tmp_c_str = (c_str);                                                           \
        if ((obj)->str != NULL) {                                                                  \
            RESET_STRING(obj);                                                                     \
        }                                                                                          \
        (obj)->str = (char*)malloc((len) + 1);                                                     \
        memcpy((obj)->str, (tmp_c_str), (len));                                                    \
        (obj)->str[len] = '\0';                                                                    \
        (obj)->length = (len);                                                                     \
    }

#ifdef __cplusplus
}
#endif

#endif  // _DAL_STRING_H_